package com.lagou.code.controller.service;

import java.util.Date;

import com.lagou.common.dao.LagouAuthCodeMapper;
import com.lagou.common.entity.LagouAuthCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created with IntelliJ IDEA by ChouFy on 2020-06-04.
 *
 * @author chouFy
 */
@Service
public class CodeService {

    @Autowired
    private LagouAuthCodeMapper lagouAuthCodeMapper;

    public Object create(String email) {

        int code = (int) ((Math.random() * 9 + 1) * 100000);

        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCode(code + "");
        lagouAuthCode.setCreatetime(new Date());
        lagouAuthCode.setExpiretime(new Date(System.currentTimeMillis() + (1000 * 60 * 10)));

        int ret = lagouAuthCodeMapper.insert(lagouAuthCode);

        if (ret > 0) {
            return true;
        }
        return false;

    }


    public Object validate(String email, String code) {

        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCode(code + "");
        lagouAuthCode = lagouAuthCodeMapper.selectOne(lagouAuthCode);

        if(lagouAuthCode != null && lagouAuthCode.getExpiretime().getTime()  > System.currentTimeMillis()){
            return true;
        }
        return false;
    }


}
